package com.jason.kotlin.gank.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.gank.api.GankService
import com.jason.kotlin.gank.model.GankDataBean
import com.jason.kotlin.gank.repository.GankApi
import com.jason.kotlin.gank.repository.GankApiImpl
import com.jason.library.common.base.BaseViewModel
import com.jason.library.common.base.DataWrapper
import kotlinx.coroutines.launch

class GankGirlViewModel(application: Application) : BaseViewModel(application) {

    val gankData = MutableLiveData<DataWrapper<List<GankDataBean>>>()

    val randomData = MutableLiveData<DataWrapper<List<GankDataBean>>>()

    val imageList = mutableListOf<String>()

    private var gankApi : GankApi = GankApiImpl()

    private var curPage: Int = 1

    fun loadData() {
        curPage = 1
        showLoading()
        loadData(curPage)
    }

    fun loadMoreData() {
        curPage++
        loadData(curPage)
    }

    fun loadData(page: Int) {
        viewModelScope.launch {
            try {
                if(page <= 1) {
                    imageList.clear()
                    val randomResponse = gankApi.getRandomData(GankService.CATEGORY_ARTICLE, GankService.TYPE_ALL,20)
                    randomData.postValue(DataWrapper.success(randomResponse.data))
                }
                val girlResponse = gankApi.loadGirlData(page)
                gankData.postValue(DataWrapper.success(girlResponse.data))
                parseImages(girlResponse.data)
                showContent()
            }catch (e:Exception) {
                showError(e.toString())
            }
        }
    }

    private fun parseImages(list: List<GankDataBean>) {
        for (i in list.indices) {
            imageList.add(list[i].url)
        }
    }
}